<template>
    <div class="page" ref="page">
        <div class="wrap">
            <ul>
                <li v-for="(item,index) in goods" :key="item.gid">{{item.title}}</li>
            </ul>
            <div style="width:100%;height:450px;"></div>
        </div>
    </div>
</template>

<script>
  import BetterScroll from 'better-scroll';
  import { request } from '../../assets/js/utils/request';

  export default {
    name: 'better-scroll',
    data(){
      return {
        goods:[]
      }
    },
    async created() {
      this.curPage=1;//当前页码
      this.pageCount=0;//总页码数
      this.bScroll=null;//BetterScroll实例
      let res=await this.getData();
      if(res.code==200){
        this.goods=res.data;
        this.pageCount=res.pageinfo.pagenum;
        this.$nextTick(()=>{
          this.bScroll = new BetterScroll(this.$refs['page'], {
            scrollY: true,//开启纵向滚动
            //开启下拉刷新
            pullDownRefresh: {
              threshold: 50,
              stop: 20
            },
            //开启上拉加载
            pullUpLoad: {
              threshold: 50
            }
          });
          this.bScroll.on('pullingDown', () => {
            console.log('下拉刷新');
            this.bScroll.finishPullDown();//告诉 better-scroll 数据已加载
          });
          this.bScroll.on('pullingUp', () => {
            console.log('上拉加载');
            this.getNextPageData(()=>{
              this.bScroll.finishPullUp();//告诉 better-scroll 数据已加载
            });
          });
        })

      }
    },
    methods:{
      getData(){
       return request(this.$config.baseApi+"/home/goods/search?kwords=&page=1&token="+this.$config.token).then(res=>{
         return res;
        });
      },
      //下一页数据
      getNextPageData(callback){
        if(this.curPage<this.pageCount){
          this.curPage++;
          request(this.$config.baseApi+"/home/goods/search?kwords=&page="+this.curPage+"&token="+this.$config.token).then(res=>{
            console.log(res)
            if(res.code==200){
              this.goods.push(...res.data);
              this.bScroll.refresh();
              if(callback){
                callback()
              }
            }
          })
        }
      }
    },
  };
</script>

<style scoped>
    .page {
        width: 100%;
        height: 96vh;
        overflow: hidden;
    }

    .wrap {
        width: 100%;
        height: auto;
    }

    .wrap li {
        width: auto;
        height: 100px;
    }
</style>
